<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 商品分类类
 * @package  htdocs
 * @subpackage  quanliadmin
 * @author   allen.qiang
 * @version 1.0
 */
class goodsCategory {

    private $dbca;

    public function __construct( $dbca ) {
        $this->dbca = $dbca;
    }
    
    /**
     * 查询大分类信息
     * @param $arg_array
     * @return array|null
     */
    public function searchBigCategory( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //大分类ID
        if (isset($arg_array['bigCategoryID']) && is_numeric($arg_array['bigCategoryID'])) {
            $sql .= ' AND bigCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['bigCategoryID'];
        }

        //使用标志
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }


        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_bigcategory ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_bigcategory ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'bigCategoryID' => $item->bigCategoryID,
                    'name' => $item->description,
                    'useFlg' => $item->useFlg,
                    'sortOrder' => $item->sortOrder,
                    'link' => $this->setCategoryLink( $item->bigCategoryID )
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询中分类信息
     * @param $arg_array
     * @return array|null
     */
    public function searchMidCategory( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //大分类ID
        if (isset($arg_array['bigCategoryID']) && is_numeric($arg_array['bigCategoryID'])) {
            $sql .= ' AND bigCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['bigCategoryID'];
        }

        //中分类ID
        if (isset($arg_array['midCategoryID']) && is_numeric($arg_array['midCategoryID'])) {
            $sql .= ' AND midCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['midCategoryID'];
        }

        //使用标志
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }


        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_midcategory ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_midcategory ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'bigCategoryID' => $item->bigCategoryID,
                    'midCategoryID' => $item->midCategoryID,
                    'name' => $item->description,
                    'useFlg' => $item->useFlg,
                    'sortOrder' => $item->sortOrder,
                    'link' => $this->setCategoryLink( $item->bigCategoryID, $item->midCategoryID )
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 查询小分类信息
     * @param $arg_array
     * @return array|null
     */
    public function searchSmallCategory( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //大分类ID
        if (isset($arg_array['bigCategoryID']) && is_numeric($arg_array['bigCategoryID'])) {
            $sql .= ' AND bigCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['bigCategoryID'];
        }

        //中分类ID
        if (isset($arg_array['midCategoryID']) && is_numeric($arg_array['midCategoryID'])) {
            $sql .= ' AND midCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['midCategoryID'];
        }

        //中分类ID
        if (isset($arg_array['smallCategoryID']) && is_numeric($arg_array['smallCategoryID'])) {
            $sql .= ' AND smallCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['smallCategoryID'];
        }

        //使用标志
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }


        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_smallcategory ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_smallcategory ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'bigCategoryID' => $item->bigCategoryID,
                    'midCategoryID' => $item->midCategoryID,
                    'smallCategoryID' => $item->smallCategoryID,
                    'name' => $item->description,
                    'useFlg' => $item->useFlg,
                    'sortOrder' => $item->sortOrder,
                    'link' => $this->setCategoryLink( $item->bigCategoryID, $item->midCategoryID, $item->smallCategoryID )
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
    
    public function setCategoryLink( $bigID, $midID = '', $smallID = '' ) {
        return G_WEBSITE_DOMAINNAME . sprintf('/shop/list-%d%s%s.html', $bigID, $midID, $smallID);
    }
    
    /**
     * 分类映射规格组
     * @param $arg_array
     * @return array|null
     */
    public function categoryMappingSpec( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //分类ID 大分类.中分类.小分类
        if (isset($arg_array['categoryID']) && !empty($arg_array['categoryID'])) {
            $sql .= ' AND categoryID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['categoryID'];
        }

        //规格组
        if (isset($arg_array['specGroupID']) && !is_numeric($arg_array['specGroupID'])) {
            $sql .= ' AND specGroupID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['specGroupID'];
        }


        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_category_specGroup ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_category_specGroup ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'categoryID' => $item->categoryID,
                    'specGroupID' => $item->specGroupID
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
    
    /**
     * 添加分类
     *
     * @param unknown_type $arg_array
     * @return unknown
     */
	public function saveCategory( $arg_array ){
		
		//参数检查
		if (!isset( $arg_array['params'] , $arg_array['params'])) {
			return array( 'code' => 400, 'message' => '参数错误');
		}
		
		if (isset($arg_array['params']['categoryID']) && !empty($arg_array['params']['categoryID'])) {	//编辑
			$editArray = explode('_', $arg_array['params']['categoryID']);
			switch ($editArray[1]) {
				case 1:	//编辑大分类
					$edit_category = new entity('goods_bigcategory');
					$edit_category->bigCategoryID = $editArray[0];
					
					//检查分类名称是否重复
					$check_categoryName = new entity('goods_bigcategory');
					
					//更新商品里面的分类名称
					$goods_list = sprintf('UPDATE goods_list SET timeStamp=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_list_edit = sprintf('UPDATE goods_list_edit SET timeStamp=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_sale = sprintf('UPDATE goods_sale SET timeStamp=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_sale_edit = sprintf('UPDATE goods_sale_edit SET timeStamp=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					
				break;
				case 2:	//编辑中分类
					$edit_category = new entity('goods_midcategory');
					$edit_category->midCategoryID = $editArray[0];
					
					$check_categoryName = new entity('goods_midcategory');
					
					//更新商品里面的分类名称
					$goods_list = sprintf('UPDATE goods_list SET timeStamp=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_list_edit = sprintf('UPDATE goods_list_edit SET timeStamp=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_sale = sprintf('UPDATE goods_sale SET timeStamp=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_sale_edit = sprintf('UPDATE goods_sale_edit SET timeStamp=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);

				break;
				case 3:	//编辑小分类
					$edit_category = new entity('goods_smallcategory');
					$edit_category->smallCategoryID = $editArray[0];
					
					$check_categoryName = new entity('goods_smallcategory');
					
					//更新商品里面的分类名称
					$goods_list = sprintf('UPDATE goods_list SET timeStamp=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_list_edit = sprintf('UPDATE goods_list_edit SET timeStamp=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_sale = sprintf('UPDATE goods_sale SET timeStamp=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_sale_edit = sprintf('UPDATE goods_sale_edit SET timeStamp=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					
				break;
				default:
					return array( 'code' => 400, 'message' => '参数错误');
				break;		
			}
			
			if (!$this->dbca->fetch($edit_category)) {
				return array( 'code' => 400, 'message' => sprintf('分类号「%s」信息未找到，请核实', $editArray[0]));
			}

			//检查名字分类名是否重复
			$check_categoryName->description = $arg_array['params']['categoryName'];
			$is_categoryName = $this->dbca->fetch($check_categoryName);
			
			switch ($editArray[1]) {
				case 1:
					if ($is_categoryName && $check_categoryName->bigCategoryID != $editArray[0]) {
						return array( 'code' => 400, 'message' => sprintf('分类名称「%s」已经存在', $arg_array['params']['categoryName']));
					}
					
					$mappingID = $edit_category->bigCategoryID;
					
					$changeID = $edit_category->bigCategoryID;
				break;
				case 2:
					if ($is_categoryName && $check_categoryName->midCategoryID != $editArray[0]) {
						return array( 'code' => 400, 'message' => sprintf('分类名称「%s」已经存在', $arg_array['params']['categoryName']));
					}
					$mappingID = $edit_category->bigCategoryID . $edit_category->midCategoryID;
					
					$changeID = $edit_category->midCategoryID;
				break;
				case 3:
					if ($is_categoryName && $check_categoryName->smallCategoryID != $editArray[0]) {
						return array( 'code' => 400, 'message' => sprintf('分类名称「%s」已经存在', $arg_array['params']['categoryName']));
					}
					
					$mappingID = $edit_category->bigCategoryID . $edit_category->midCategoryID . $edit_category->smallCategoryID;
					$changeID = $edit_category->smallCategoryID;
				break;	
			}
				
			$edit_category->description = $arg_array['params']['categoryName'];
			$edit_category->editor      = $arg_array['creator'];
			$edit_category->tagID       = 0;

		} else {	//添加
			
			$addArray = explode('_', $arg_array['params']['parentID']);
			switch ($addArray[2]) {
				case 1:	//添加大分类
				
					$save_category = new entity('goods_bigcategory');
					
					//最大排序
					$maxSort = $this->dbca->stmt_query('SELECT MAX(sortOrder)+1 maxSort FROM goods_bigcategory');
				
					//检查分类名称是否重复
					$check_categoryName = new entity('goods_bigcategory');
					
					//最大分类ID
					$max_sql = 'SELECT MAX(bigCategoryID) maxID FROM goods_bigcategory';
					
				break;	
				case 2:	//添加中分类
				
					$save_category = new entity('goods_midcategory');
					$save_category->bigCategoryID = $addArray[0];
					
					//最大排序
					$maxSort = $this->dbca->stmt_query('SELECT MAX(sortOrder)+1 maxSort FROM goods_midcategory');
				
					$check_categoryName = new entity('goods_midcategory');
					
					$mappingID = $addArray[0];
					
					//最大分类ID
					$max_sql = 'SELECT MAX(midCategoryID) maxID FROM goods_midcategory';
				break;	
				case 3:	//添加小分类
				
					$save_category = new entity('goods_smallcategory');
					$save_category->bigCategoryID = $addArray[0];
					$save_category->midCategoryID = $addArray[1];
					
					//最大排序
					$maxSort = $this->dbca->stmt_query('SELECT MAX(sortOrder)+1 maxSort FROM goods_smallcategory');
				
					$check_categoryName = new entity('goods_smallcategory');
					
					$mappingID = $addArray[0] . $addArray[1];
					
					//最大分类ID
					$max_sql = 'SELECT MAX(smallCategoryID) maxID FROM goods_smallcategory';
					
				break;
				default:
					return array( 'code' => 400, 'message' => '参数错误');
				break;	
			}
			
			//检查分类名称是否重复
			$check_categoryName->description = $arg_array['params']['categoryName'];
			if ($this->dbca->fetch($check_categoryName)) {
				return array( 'code' => 400, 'message' => sprintf('分类名称「%s」已经存在', $arg_array['params']['categoryName']));
			}
			
			$save_category->creator     = $arg_array['creator'];
			$save_category->description = $arg_array['params']['categoryName'];
			$save_category->tagID       = 0;
			$save_category->useFlg      = 1;
			$save_category->sortOrder   = $maxSort[0]->maxSort == 0 ? 1 : $maxSort[0]->maxSort;
			
		}
		
		$this->dbca->beginTransaction();
		try {
			if (isset($arg_array['params']['categoryID']) && !empty($arg_array['params']['categoryID'])){
				$this->dbca->save($edit_category);
	
				$this->dbca->stmt_query($goods_list);
				$this->dbca->stmt_query($goods_list_edit);
				$this->dbca->stmt_query($goods_sale);
				$this->dbca->stmt_query($goods_sale_edit);
				
				$data = array(
					'categoryName' => $arg_array['params']['categoryName'],
					'categoryID'   => isset($changeID) ? $changeID : 0,
					'type'		   => 2
				);
			} else {
				$this->dbca->save($save_category);
				
				$maxID = $this->dbca->stmt_query($max_sql);
				if (!isset($mappingID) || empty($mappingID)) {
					$mappingID = $maxID[0]->maxID;
				} else {
					$mappingID .= $maxID[0]->maxID;
				}
				
				$data = array('type' => 1);
				
			}
			
			//添加规格组、标签组对应关系
			if (isset($arg_array['params']['specGroupID'])) {
				//删除旧的对应关系
				$this->dbca->stmt_query('DELETE FROM goods_category_specGroup WHERE categoryID = ?', 's', $mappingID);
				
				foreach ($arg_array['params']['specGroupID'] as $specGroupID) {
					$goods_category_specGroup = new entity('goods_category_specGroup');
					$goods_category_specGroup->creator     = $arg_array['creator'];
					$goods_category_specGroup->categoryID  = $mappingID;
					$goods_category_specGroup->specGroupID = $specGroupID;
					
					$this->dbca->save($goods_category_specGroup);
				}
			}

			$this->dbca->commit();
			if (isset($arg_array['params']['categoryID']) && !empty($arg_array['params']['categoryID'])){
				return array( 'code' => 200, 'message' => '商品分类更新成功', 'data' => $data);
			} else {
				return array( 'code' => 200, 'message' => '商品分类保存成功', 'data' => $data);
			}
			
		}catch(Exception $e){
			error_log($e->getMessage());
			$this->dbca->rollBack();
			if (isset($arg_array['params']['categoryID']) && !empty($arg_array['params']['categoryID'])){
				return array( 'code' => 400, 'message' => '商品分类更新失败');
			} else {
				return array( 'code' => 400, 'message' => '商品分类保存失败');
			}
		}
	}
	
	/**
	 * 更新商品分类使用状态
	 *
	 * @param unknown_type $arg_array
	 * @return unknown
	 */
	public function categoryUse ( $arg_array ) {
		
		//检查参数
		if (!isset($arg_array['categoryID'], $arg_array['useFlg'], $arg_array['level'])) {
            return array('code' => 400, 'message' => '缺少参数' );
		}
		
		if (!in_array($arg_array['useFlg'], array(0, 1)) || !in_array($arg_array['level'], array(1, 2, 3))) {
			return array('code' => 400, 'message' => '参数错误，请核实' );
		}
		
		//根据分类去执行对应操作
		switch ($arg_array['level']){
			case 1:	//大分类
				$change_category = new entity('goods_bigcategory');
				$change_category->bigCategoryID = $arg_array['categoryID'];
			break;	
			case 2:	//中分类
				$change_category = new entity('goods_midcategory');
				$change_category->midCategoryID = $arg_array['categoryID'];
			break;
			case 3:	//小分类
				$change_category = new entity('goods_smallcategory');
				$change_category->smallCategoryID = $arg_array['categoryID'];
			break;
		}
		
		if (!$this->dbca->fetch($change_category)) {
			return array('code' => 400, 'message' => sprintf('分类号「%d」信息未找到，请核实', $arg_array['categoryID']) );
		}
        
		$change_category->useFlg = $arg_array['useFlg'];
		
		try {
			
			$this->dbca->save($change_category);
			
			$data = array(
				'categoryID' => $arg_array['categoryID'],
				'useFlg' 	 => $arg_array['useFlg'],
				'level'		 => $arg_array['level'],
				'type'       => 1
			);
			
			return array('code' => 200, 'message' => '商品分类使用状态更新成功', 'data' => $data );
			
		}catch (Exception $e){
			
			error_log($e->getMessage());
			
			return array('code' => 400, 'message' => '商品分类使用状态更新失败' );
		}
		
	}
	
	/**
     * 修改分类名称
     *
     * @param unknown_type $arg_array
     * @return unknown
     */
     public function changeName($arg_array){
    	
    	//检查参数
    	if (!isset($arg_array['categoryID'], $arg_array['level'], $arg_array['categoryName'])) {
    		return array(
    			'code' 	  => 400, 
    			'message' => '缺少参数', 
    			'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
    		);
    	}
    	
    	switch ($arg_array['level']) {
    		case 1:	//大分类
    			$sort_category = new entity('goods_bigcategory');
    			
    			$save_category = new entity('goods_bigcategory');
    			$save_category->bigCategoryID = $arg_array['categoryID'];
    			
    			//更新商品里面的分类名称
				$goods_list = sprintf('UPDATE goods_list SET TIMESTAMP=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_list_edit = sprintf('UPDATE goods_list_edit SET TIMESTAMP=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_sale = sprintf('UPDATE goods_sale SET TIMESTAMP=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_sale_edit = sprintf('UPDATE goods_sale_edit SET TIMESTAMP=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				
    		break;
    		case 2:	//中分类
    			$sort_category = new entity('goods_midcategory');
    			
    			$save_category = new entity('goods_midcategory');
    			$save_category->midCategoryID = $arg_array['categoryID'];
    			
    			//更新商品里面的分类名称
				$goods_list = sprintf('UPDATE goods_list SET TIMESTAMP=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_list_edit = sprintf('UPDATE goods_list_edit SET TIMESTAMP=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_sale = sprintf('UPDATE goods_sale SET TIMESTAMP=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_sale_edit = sprintf('UPDATE goods_sale_edit SET TIMESTAMP=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
    			
    		break;
    		case 3:	//小分类
    			$sort_category = new entity('goods_smallcategory');
    			
    			$save_category = new entity('goods_smallcategory');
    			$save_category->smallCategoryID = $arg_array['categoryID'];
    			
    			//更新商品里面的分类名称
				$goods_list = sprintf('UPDATE goods_list SET TIMESTAMP=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_list_edit = sprintf('UPDATE goods_list_edit SET TIMESTAMP=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_sale = sprintf('UPDATE goods_sale SET TIMESTAMP=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_sale_edit = sprintf('UPDATE goods_sale_edit SET TIMESTAMP=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
    			
    		break;
    		default:
    			return array(
    				'code'   => 400, 
    				'message' => '参数错误', 
    				'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
    			);	
    		break;	
    	}

    	if (!$this->dbca->fetch($save_category)) {
    		return array(
    			'code'    => 400, 
    			'message' => sprintf('分类号「%s」信息未找到，请核实', $arg_array['categoryID']), 
    			'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
    		);	
    	}
    	
    	//分类是否重复
    	$sort_category->description = $arg_array['categoryName'];
    	if ($this->dbca->fetch($sort_category)) {
    		switch ($arg_array['level']) {
    			case 1:
    				if ($sort_category->bigCategoryID != $arg_array['categoryID']) {
    					return array(
    						'code'    => 400, 
    						'message' => sprintf('分类名称「%s」已经存在', $arg_array['categoryName']), 
    						'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
    					);	
    				}
    			break;	
    			case 2:
    				if ($sort_category->midCategoryID != $arg_array['categoryID']) {
    					return array(
    						'code'    => 400, 
    						'message' => sprintf('分类名称「%s」已经存在', $arg_array['categoryName']), 
    						'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
    					);
    				}
    			break;
    			case 3:
    				if ($sort_category->smallCategoryID != $arg_array['categoryID']) {
    					return array(
    						'code'    => 400, 
    						'message' => sprintf('分类名称「%s」已经存在', $arg_array['categoryName']), 
    						'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
    					);
    				}
    			break;
    		}
    	}
    	
    	$save_category->description = $arg_array['categoryName'];
    	
    	$this->dbca->beginTransaction();
    	try {
    		$this->dbca->save($save_category);
    		
    		$this->dbca->stmt_query($goods_list);
    		$this->dbca->stmt_query($goods_list_edit);
    		$this->dbca->stmt_query($goods_sale);
    		$this->dbca->stmt_query($goods_sale_edit);
    		
    		$this->dbca->commit();
    		
    		return array('code' => 200, 'message' => '排序修改成功');
    		
    	}catch (Exception $e) {
    		$this->dbca->rollBack();
    		return array(
				'code'    => 400, 
				'message' => '分类名称修改失败', 
				'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
			);
    	}

    }
    
    /**
     * 修改分类排序
     *
     */
    public function changeSort($arg_array){
    	
    	//检查参数
    	if (!isset($arg_array['categoryID'], $arg_array['level'], $arg_array['sortOrder'])) {
    		return array('code' => 400, 'message' => '缺少参数', 'data' => array('categoryID' =>$arg_array['categoryID'], 'type' => 1));
    	}
    	
    	switch ($arg_array['level']) {
    		case 1:	//大分类
    			$sort_category = new entity('goods_bigcategory');
    			$sort_category->sortOrder = $arg_array['sortOrder'];
    			
    			$save_category = new entity('goods_bigcategory');
    			$save_category->bigCategoryID = $arg_array['categoryID'];
    		break;
    		case 2:	//中分类
    			$sort_category = new entity('goods_midcategory');
    			$sort_category->sortOrder = $arg_array['sortOrder'];
    			
    			$save_category = new entity('goods_midcategory');
    			$save_category->midCategoryID = $arg_array['categoryID'];
    		break;
    		case 3:	//小分类
    			$sort_category = new entity('goods_smallcategory');
    			$sort_category->sortOrder = $arg_array['sortOrder'];
    			
    			$save_category = new entity('goods_smallcategory');
    			$save_category->smallCategoryID = $arg_array['categoryID'];
    		break;
    		default:
    			return array('code' => 400, 'message' => '参数错误', 'data' => array('categoryID' =>$arg_array['categoryID'], 'type' => 1));	
    		break;	
    	}
    	
    	if (!$this->dbca->fetch($save_category)) {
    		return array('code' => 400, 'message' => sprintf('分类号「%s」信息未找到，请核实', $arg_array['categoryID']), 'data' => array('categoryID' =>$arg_array['categoryID'], 'type' => 1));	
    	}
    	
    	if ($this->dbca->fetch($sort_category)) {
    		switch ($arg_array['level']) {
    			case 1:
    				if ($sort_category->bigCategoryID != $arg_array['categoryID']) {
    					return array('code' => 400, 'message' => sprintf('排序「%s」已经存在', $arg_array['sortOrder']), 'data' => array('categoryID' =>$arg_array['categoryID'], 'type' => 1));	
    				}
    			break;	
    			case 2:
    				if ($sort_category->midCategoryID != $arg_array['categoryID']) {
    					return array('code' => 400, 'message' => sprintf('排序「%s」已经存在', $arg_array['sortOrder']), 'data' => array('categoryID' =>$arg_array['categoryID'], 'type' => 1));	
    				}
    			break;
    			case 3:
    				if ($sort_category->smallCategoryID != $arg_array['categoryID']) {
    					return array('code' => 400, 'message' => sprintf('排序「%s」已经存在', $arg_array['sortOrder']), 'data' => array('categoryID' =>$arg_array['categoryID'], 'type' => 1));	
    				}
    			break;
    		}
    	}
    	
    	$save_category->sortOrder = $arg_array['sortOrder'];
    	$this->dbca->save($save_category);

    	return array('code' => 200, 'message' => '排序修改成功');
    }
    
    /**
	 * 删除分类
	 *
	 */
	public function deleteCategory ( $arg_array ) {
		
		//检查参数
		if (!isset($arg_array['categoryID'], $arg_array['level'])) {
			return array( 'code' => 400, 'message' => '缺少参数' );
		}
		
		if (!in_array($arg_array['level'], array(1, 2, 3))) {
			return array( 'code' => 400, 'message' => '参数错误' );
		}
		
		//检查删除的是否是子分类
		switch ($arg_array['level']) {
			case 1:	//大分类
				$goods_midcategory = new entity('goods_midcategory');
				$goods_midcategory->bigCategoryID = $arg_array['categoryID'];
				if ($this->dbca->fetch($goods_midcategory)) {
					return array( 'code' => 400, 'message' => '请先删除子分类' );
				}
				
				$goods_smallcategory = new entity('goods_smallcategory');
				$goods_smallcategory->bigCategoryID = $arg_array['categoryID'];
				if ($this->dbca->fetch($goods_smallcategory)) {
					return array( 'code' => 400, 'message' => '请先删除子分类' );
				}
				
				//检查分类是否存在商品
				$goods_list      = sprintf('SELECT * FROM goods_list WHERE bigCategoryID = %s', $arg_array['categoryID']);
				$goods_list_edit = sprintf('SELECT * FROM goods_list_edit WHERE bigCategoryID = %s', $arg_array['categoryID']);
				$goods_sale      = sprintf('SELECT * FROM goods_sale WHERE bigCategoryID = %s', $arg_array['categoryID']);
				$goods_sale_edit = sprintf('SELECT * FROM goods_sale_edit WHERE bigCategoryID = %s', $arg_array['categoryID']);
				
				//删除分类sql
				$category_sql = sprintf('DELETE FROM goods_bigcategory WHERE bigCategoryID = %s', $arg_array['categoryID']);
				
			break;	
            case 2:	//中分类
				$goods_smallcategory = new entity('goods_smallcategory');
				$goods_smallcategory->midCategoryID = $arg_array['categoryID'];
				if ($this->dbca->fetch($goods_smallcategory)) {
					return array( 'code' => 400, 'message' => '请先删除子分类' );
				}
				
				//检查分类是否存在商品
				$goods_list      = sprintf('SELECT * FROM goods_list WHERE midCategoryID = %s', $arg_array['categoryID']);
				$goods_list_edit = sprintf('SELECT * FROM goods_list_edit WHERE midCategoryID = %s', $arg_array['categoryID']);
				$goods_sale      = sprintf('SELECT * FROM goods_sale WHERE midCategoryID = %s', $arg_array['categoryID']);
				$goods_sale_edit = sprintf('SELECT * FROM goods_sale_edit WHERE midCategoryID = %s', $arg_array['categoryID']);
				
				$category_sql = sprintf('DELETE FROM goods_midcategory WHERE midCategoryID = %s', $arg_array['categoryID']);
				
			break;	
            case 3:
           		//检查分类是否存在商品
				$goods_list      = sprintf('SELECT * FROM goods_list WHERE smallCategoryID = %s', $arg_array['categoryID']);
				$goods_list_edit = sprintf('SELECT * FROM goods_list_edit WHERE smallCategoryID = %s', $arg_array['categoryID']);
				$goods_sale      = sprintf('SELECT * FROM goods_sale WHERE smallCategoryID = %s', $arg_array['categoryID']);
				$goods_sale_edit = sprintf('SELECT * FROM goods_sale_edit WHERE smallCategoryID = %s', $arg_array['categoryID']);
				
				$category_sql = sprintf('DELETE FROM goods_smallcategory WHERE smallCategoryID = %s', $arg_array['categoryID']);	
            break;	
		}
		
		//删除的分类是否有商品
		$check_goods_list      = $this->dbca->stmt_query($goods_list);
		$check_goods_list_edit = $this->dbca->stmt_query($goods_list_edit);
		$check_goods_sale      = $this->dbca->stmt_query($goods_sale);
		$check_goods_sale_edit = $this->dbca->stmt_query($goods_sale_edit);
		
		if ($check_goods_list || $check_goods_list_edit || $check_goods_sale || $check_goods_sale_edit) {
			return array( 'code' => 400, 'message' => '当前分类存在对应的商品信息，不能删除' );
		}

		//删除分类
		$this->dbca->stmt_query($category_sql);
		
		$data = array(
			'type'       => 2,
			'categoryID' => $arg_array['categoryID']
		);
		return array( 'code' => 200, 'message' => '商品分类删除成功', 'data' => $data );
	}
}